const { exec } = require('../db/mysql');

const getList = (author, keyword) => {
  /**
   * 如果没有1=1，若author/keyword不存在，会语法错误；
   */
  // 1=1 仅仅是为了语法规范；
  let sql = `select * from blogs where 1=1 `
  if(author) {
    sql += `and author='${author}' `;
  }
  if(keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += `order by createtime desc;`
  return exec(sql);
}

const getDetail = id => {
  const sql = `select * from blogs where id='${id}'`

  return exec(sql).then(rows => {
    return rows[0];
  });
}

const newBlog = (blogData = {}) => {
  const title = blogData.title;
  const content = blogData.content;
  const author = blogData.author;
  const createtime = Date.now();

  const sql = `insert into blogs(title, content, author, createtime) values('${title}', '${content}', '${author}', '${createtime}') `;

  return exec(sql).then(newBlog => {
    return {
      id: newBlog.insertId
    }
  });
}

const updateBlog = (id, blogData = {}) => {
  const title = blogData.title;
  const content = blogData.content;
  const sql = `
    update blogs set title='${title}',content='${content}'
    where id='${id}'
  `;

  return exec(sql).then(updateBlog => {
    if(updateBlog.affectedRows > 0) {
      return true;
    }
    return false;
  });
}
const delBlog = (id, author) => {
  // author保证只能删除自己的内容；
  const sql = `
    delete from blogs where id='${id}' and author='${author}'`;

  return exec(sql).then(updateBlog => {
    if(updateBlog.affectedRows > 0) {
      return true;
    }
    return false;
  });
}
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
}
